package com.arpa.wms.service.impl;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.wms.cache.CarrierCache;
import com.arpa.wms.cache.ShopCache;
import com.arpa.wms.common.ess.*;
import com.arpa.wms.common.util.ArpaCloudUtil;
import com.arpa.wms.common.util.DouyinUtil;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.consts.ResultDO;
import com.arpa.wms.domain.dto.DeliveryDTO;
import com.arpa.wms.domain.dto.DeliveryItemDTO;
import com.arpa.wms.domain.dto.SplitOrderDTO;
import com.arpa.wms.domain.entity.*;
import com.arpa.wms.domain.enums.DeliveryStatusEnum;
import com.arpa.wms.domain.enums.SourcePlatformEnum;
import com.arpa.wms.domain.vo.*;
import com.arpa.wms.mapper.SplitOrderMapper;
import com.arpa.wms.service.IDeliveryItemService;
import com.arpa.wms.service.IDeliveryService;
import com.arpa.wms.service.SplitOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

/**
 * @author liuxr
 * @date 2021年12月23日 16:45
 */
@Service
@Log4j2
public class SplitOrderServiceIpml extends ServiceImpl<SplitOrderMapper, SplitOrder> implements SplitOrderService {

    @Autowired
    private IDeliveryService deliveryService;
    @Autowired
    private IDeliveryItemService deliveryItemService;
    @Resource
    private ArpaCloudUtil arpaCloudUtil;
    @Resource
    private CarrierCache carrierCache;
    @Resource
    private ShopCache shopCache;
    private final static String COMMA = ",";
    @Autowired
    private PartyCache partyCache;
    /**
     * 根据运单号获取订单信息
     *
     * @param code
     * @return com.arpa.wms.domain.vo.DeliverySplitOrderVo
     * @author liuxr
     * @date 2021/12/23 16:46
     */
    @Override
    public DeliverySplitOrderVo getDeliverySplitOrderVoByWaybillCode(String code) {
        Delivery delivery = deliveryService.getOne(Wrappers.lambdaQuery(Delivery.class)
                .select(Delivery::getCarrierName,
                        Delivery::getCode,
                        Delivery::getOrderNum,
                        Delivery::getOrderTag,
                        Delivery::getShipmentName,
                        Delivery::getWavePickingCode,
                        Delivery::getWaybillCode,
                        Delivery::getSplitWaybillCode,
                        Delivery::getPackageNum)
                .and(wrapper->wrapper.eq(Delivery::getCode, code).or().eq(Delivery::getWaybillCode, code))
                .notIn(Delivery::getStatus, "0","1","2","3","4","5","6")
                .eq(Delivery::getIsCancel, NumConst.NUM_ZERO));
        if (delivery == null) {
            throw new ServiceException("找不到符合条件的订单信息");
        }
        DeliverySplitOrderVo vo = new DeliverySplitOrderVo();
        vo.setCarrierName(delivery.getCarrierName());
        vo.setCode(delivery.getCode());
        vo.setOrderNum(delivery.getOrderNum());
        vo.setOrderTag(delivery.getOrderTag());
        vo.setShipmentName(delivery.getShipmentName());
        vo.setWavePickingCode(delivery.getWavePickingCode());
        vo.setWaybillCode(delivery.getWaybillCode());
        vo.setSplitWaybillCode(delivery.getSplitWaybillCode());
        vo.setPackageNum(delivery.getPackageNum());

        List<DeliveryItem> deliveryItemList = deliveryItemService.list(Wrappers.lambdaQuery(DeliveryItem.class)
                .eq(DeliveryItem::getDeliveryCode, delivery.getCode()));
        List<DeliverySplitOrderItemVo> items = deliveryItemList.stream().map(r -> {
            DeliverySplitOrderItemVo itemVo = new DeliverySplitOrderItemVo();
            itemVo.setGoodCode(r.getGoodCode());
            itemVo.setGoodsBarCode(r.getGoodsBarCode());
            itemVo.setGoodsName(r.getGoodsName());
            itemVo.setQuantity(r.getQuantity());
            itemVo.setGoodsUnitName(r.getGoodsUnitName());
            return itemVo;
        }).collect(Collectors.toList());
        vo.setItems(items);

        return vo;
    }


    /**
     * 拆分
     *
     * @param code
     * @author liuxr
     * @date 2021/12/23 17:25
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void split(String code, Integer splitPackageNum) {
        //拆单数量
        int splitNum = 10;
        //校验拆包次数
        Delivery delivery = deliveryService.getOne(new LambdaQueryWrapper<Delivery>()
                .select(Delivery::getCode,Delivery::getPackageNum,Delivery::getSplitWaybillCode).eq(Delivery::getCode, code));
        Integer packageNum = null == delivery.getPackageNum() ? NumConst.NUM_ZERO : delivery.getPackageNum();
        String splitWaybillCode = StrUtil.isEmpty(delivery.getSplitWaybillCode()) ? StrUtil.EMPTY : delivery.getSplitWaybillCode() + COMMA;
        //totalPackageNum ：总的拆分包裹数 = 包裹数量 + 拆分包裹数量 - 1
        Integer totalPackageNum = packageNum + splitPackageNum - 1;
        if (totalPackageNum > splitNum) {
            throw new ServiceException("拆分包裹数最多拆分10个");
        }
        List<SplitOrder> splitOrders = Lists.newArrayList();
        Set<String> wayBillCode =  batchGetWaybillCode(code, splitPackageNum,splitOrders);
        if(IterUtil.isEmpty(wayBillCode)){
            throw new ServiceException("未获取到面单号，拆单失败");
        }
        packageNum = packageNum + wayBillCode.size();
        splitWaybillCode = splitWaybillCode + wayBillCode.stream().collect(joining(","));
        deliveryService.update(Wrappers.lambdaUpdate(Delivery.class)
                .eq(Delivery::getCode,code)
                .set(Delivery::getPackageNum,packageNum)
                .set(Delivery::getSplitWaybillCode,splitWaybillCode)
        );
        //批量保存订单拆分信息
        this.saveBatch(splitOrders);
    }


    /**
     * 获取拆单面单号
     *
     * @param code       订单号
     * @param splitPackageNum 拆单数量
     */
    public Set<String> batchGetWaybillCode(String code, Integer splitPackageNum,List<SplitOrder> splitOrders) {
        log.info("拆单获取面单号，订单号：{}，拆单数量：{}", JSONUtil.toJsonStr(code),splitPackageNum);
        Delivery delivery = deliveryService.getOne(Wrappers.lambdaQuery(Delivery.class)
                .select(Delivery::getId,
                        Delivery::getCode,
                        Delivery::getCarrierType,
                        Delivery::getWaybillCode,
                        Delivery::getLogisticsCode,
                        Delivery::getShipmentCode,
                        Delivery::getCarrierCode,
                        Delivery::getSenderProvince,
                        Delivery::getSenderCity,
                        Delivery::getSenderDistrict,
                        Delivery::getSenderDetailAddress,
                        Delivery::getSenderName,
                        Delivery::getSenderMobile,
                        Delivery::getSourceType,
                        Delivery::getDeliveryOrderCode,
                        Delivery::getSourcePlatformCode,
                        Delivery::getReceiverProvince,
                        Delivery::getReceiverCity,
                        Delivery::getReceiverDistrict,
                        Delivery::getReceiverDetailAddress,
                        Delivery::getReceiverName,
                        Delivery::getReceiverMobile,
                        Delivery::getIsvCode,
                        Delivery::getUserId,
                        Delivery::getOaid,
                        Delivery::getTid,
                        Delivery::getStatus,
                        Delivery::getIsCancel,
                        Delivery::getPackageNum,
                        Delivery::getTemplateUrl,
                        Delivery::getGroupCode
                )
                .eq(Delivery::getCode, code));


        Carrier carriers = carrierCache.getCarrier(delivery.getCarrierCode());
        if (null == carriers) {
            log.error("找不到承运商信息，无法获取面单号。");
            throw new ServiceException("找不到承运商信息");
        }
        //客户token
        String dynamicToken = StrUtil.EMPTY;
        //重新赋值店铺授权token
        String shopCode = carriers.getShopCode();
        if (StrUtil.isBlank(shopCode)) {
            log.error("找不到承运商对应的店铺信息，无法获取面单号。");
            throw new ServiceException("找不到承运商对应的店铺信息");
        }
        Shop shop = shopCache.getShop(shopCode);
        if (null == shop) {
            log.error("找不到承运商对应的店铺信息，无法获取面单号。");
            throw new ServiceException("找不到承运商对应的店铺信息");
        }
        if (StrUtil.isNotBlank(shop.getAccessToken())) {
            dynamicToken = shop.getAccessToken();
        }
        int type = 1;
        switch (carriers.getPlatformType()) {
            case "JD": {
                if (!StrUtil.equals(delivery.getSourcePlatformCode(), "JD")) {
                    throw new ServiceException("订单销售平台与承运商平台类型不匹配");
                }
                type = 2;
                break;
            }
            case "PDD": {
                if (!StrUtil.equalsAny(delivery.getSourcePlatformCode(), "PDD", "PIN_DUO_DUO")) {
                    throw new ServiceException("订单销售平台与承运商平台类型不匹配");
                }
                type = 3;
                break;
            }
            case "DY": {
                if (!StrUtil.equalsAny(delivery.getSourcePlatformCode(), "DY", "DYXD")) {
                    throw new ServiceException("订单销售平台与承运商平台类型不匹配");
                }
                type = 4;
                break;
            }
            case "KS": {
                if (!StrUtil.equalsAny(delivery.getSourcePlatformCode(), "KS", "KUAI_SHOU")) {
                    throw new ServiceException("订单销售平台与承运商平台类型不匹配");
                }
                type = 6;
                break;
            }
            case "TB": {
               /* if (!StrUtil.equalsAny(delivery.getSourcePlatformCode(), "TB", "TM")) {
                    throw new ServiceException("订单销售平台与承运商平台类型不匹配");
                }*/
                type = 5;
                break;
            }
            default: {

            }
        }

        List<Integer> failCodes = Lists.newArrayList();
        // 线程结果集
        Map<Integer, Future<Boolean>> futureMap = Maps.newHashMap();
        //承运商外部编码（快递编码）
        String outerCode = carriers.getOuterCode();
        //模板地址
        String standardTemplateUrl = carriers.getStandardTemplateUrl();

        if (StrUtil.hasBlank(dynamicToken, outerCode)) {
            log.error("无法获取面单号，承运商缺少必须要信息。{}", carriers);
            throw new ServiceException("无法获取面单号，承运商缺少必须要信息。");
        }

        Set<String> wayBillCodeSet = new HashSet<>();
        //已经拆单的包裹数（总包裹数-1）
        int splitedPackageNum = delivery.getPackageNum() - 1;
        //拆单的总包裹数
        int totalSplitPackageNum = splitedPackageNum + splitPackageNum;
        for (int i = splitedPackageNum; i < totalSplitPackageNum; i++) {
            ElectronicFaceSheetDTO dto = genElectronicFaceSheetDTO(carriers, delivery, dynamicToken, outerCode, standardTemplateUrl, type, shop, i);
            Map<String,Object> resultMap =  getWaybillCodeByDeliverys(dto, UserUtil.getBranchCode(), delivery.getCode(),i);
            String wayBillCode = MapUtil.get(resultMap, "wayBillCode", String.class);
            wayBillCodeSet.add(wayBillCode);
            //新增拆单记录
            splitOrders.add(genSplitOrder(delivery,resultMap));
        }

        return wayBillCodeSet;

    }

    private SplitOrder genSplitOrder(Delivery delivery,Map<String,Object> resultMap){
        SplitOrder splitOrder = new SplitOrder();
        splitOrder.setCode(IdUtil.simpleUUID());
        splitOrder.setDeliveryCode(delivery.getCode());
        splitOrder.setSplitWaybillCode(MapUtil.get(resultMap, "wayBillCode", String.class));
        splitOrder.setTemplateUrl(delivery.getTemplateUrl());
        splitOrder.setPrintData(MapUtil.get(resultMap, "printData", String.class));
        splitOrder.setGroupCode(delivery.getGroupCode());
        splitOrder.setCreatedBy(UserUtil.getCode());
        splitOrder.setCreatedName(partyCache.translate(UserUtil.getCode()));
        splitOrder.setGmtCreated(LocalDateTime.now());
        return splitOrder;
    }
    /**
     * 调用中台获取面单号
     * @author liuxr
     * @date 2021/12/24 9:39
     * @param dto
     * @param branchCode
     * @param deliveryCode
     * @param packageNum
     * @return java.lang.String
     */
    private Map<String,Object> getWaybillCodeByDeliverys(ElectronicFaceSheetDTO dto, String branchCode, String deliveryCode,int packageNum) {
        Map<String, Object> resultMap = Maps.newHashMap();
        ResultDO resultDO = arpaCloudUtil.getWaybillPrintData(dto, branchCode);
        if (resultDO.getStatus() != 0) {
            JSONObject result = null;
            String msg = StrUtil.EMPTY;
            try {
                result = JSONUtil.parseObj(resultDO.getData());
                msg = (String) result.get("msg");
            } catch (Exception e) {
                //如果解析为JSONObject报异常，在尝试解析为List
                List<Map> resultMapList = JSONUtil.toList(JSONUtil.toJsonStr(resultDO.getData()), Map.class);
                if (IterUtil.isEmpty(resultMapList)){
                    throw new ServiceException("获取面单异常，异常信息为：" + JSONUtil.toJsonStr(resultDO.getData()));
                } else {
                    msg = (String)resultMapList.get(NumConst.NUM_ZERO).get("msg");
                }
            }
            log.error("{}:{}", "获取面单失败：电子面单服务异常", msg);
            throw new ServiceException("获取面单失败：电子面单服务异常" + msg);
        }
        List<ESSElectronicFaceSheetVO> voList = JSONUtil.toList(JSONUtil.toJsonStr(resultDO.getData()), ESSElectronicFaceSheetVO.class);
        for (ESSElectronicFaceSheetVO waybillCloudPrintResponse : voList) {
            String code = waybillCloudPrintResponse.getObjectId();
            String wayBillCode = waybillCloudPrintResponse.getWaybillCode();
            if(StrUtil.isNotBlank(wayBillCode)){
                resultMap.put("wayBillCode", wayBillCode);
                resultMap.put("printData", waybillCloudPrintResponse.getPrintData());
                return resultMap;
            }else{
                throw new ServiceException("获取面单失败：没有获取到电子面单");
            }
        }
        return resultMap;
    }


    private ElectronicFaceSheetDTO genElectronicFaceSheetDTO(Carrier carriers, Delivery delivery,
                                                            String dynamicToken,
                                                            String outCode,
                                                            String standardTemplateUrl,
                                                            int type, Shop shop, int packageNum) {
        ElectronicFaceSheetDTO dto = new ElectronicFaceSheetDTO();
        dto.setType(type);
        // 寄件地址，这里的地址需要是卖家订购电子面单服务时使用的订购地址，具体可以通过TMS_WAYBILL_SUBSCRIPTION_QUERY接口获取
        AddressDto sendAddress = new AddressDto();
        sendAddress.setProvince(carriers.getProvince());
        sendAddress.setCity(carriers.getCity());
        sendAddress.setDistrict(carriers.getCounty());
        sendAddress.setDetail(carriers.getAddress());

        // 发件人信息
        UserInfoDto sender = new UserInfoDto();
        // 发件人姓名
        sender.setName(delivery.getSenderName());
        // 发件人手机号
        sender.setMobile(delivery.getSenderMobile());
        sender.setPhone(delivery.getSenderMobile());
        sender.setAddress(sendAddress);
        //sender.setOaid(delivery.getOaid());
        //sender.setTid(delivery.getTid());


        // 配送公司编码
        dto.setCpCode(outCode);
        dto.setSender(sender);
        dto.setDynamicToken(dynamicToken);

        ArrayList<TradeOrderInfoDto> orderInfoDtos = new ArrayList<>();

        List<DeliveryItem> deliveryItems = this.deliveryItemService.list(Wrappers.lambdaQuery(DeliveryItem.class)
                .eq(DeliveryItem::getDeliveryCode, delivery.getCode()));
        ArrayList<String> orderList = new ArrayList<>();
        if (StrUtil.equals(delivery.getSourceType(), "qimen")) {
            // 订单列表，这里的场景是一个订单获取一个面单号
            //处理合单的问题
            hedan(delivery);
            //京东2，拼多多3，抖音4，淘宝5，菜鸟1，快手6
            switch (type) {
                case 2:
                case 4:
                    orderList.add(delivery.getIsvCode());
                    break;
                case 6:
                    orderList.add(delivery.getIsvCode());
                    break;
                case 5:
//                    orderList.add(delivery.getIsvCode() + "_" + packageNum);
                    orderList.add(delivery.getIsvCode());
                    break;
                default:
//                    orderList.add(delivery.getDeliveryOrderCode() + "_" + packageNum);
                    orderList.add(delivery.getDeliveryOrderCode());
            }
        } else {
//            orderList.add(delivery.getCode() + "_" + packageNum);
            orderList.add(delivery.getCode());
        }
        OrderInfoDto orderInfoDto = new OrderInfoDto();
        if(type == 6){
            orderInfoDto.setOrderChannelsType("KUAI_SHOU");
        }else{
            SourcePlatformEnum oct = SourcePlatformEnum.getByValue(delivery.getSourcePlatformCode());
            if (null == oct) {
                orderInfoDto.setOrderChannelsType(SourcePlatformEnum.OTHERS.getValue());
            } else {
                orderInfoDto.setOrderChannelsType(delivery.getSourcePlatformCode());
            }
        }

        orderInfoDto.setTradeOrderList(orderList);

        if (IterUtil.isEmpty(deliveryItems)) {
            log.error("找不到订单明细，订单标识：{}", delivery.getCode());
            throw new ServiceException("找不到订单明细，订单标识：" + delivery.getCode());
        }
        List<Item> items = deliveryItems.stream().map(e1 -> {
            Item item = new Item();
            item.setName(e1.getGoodsName());
            item.setCount(e1.getQuantity().intValue());
            return item;
        }).collect(toList());

        PackageInfoDto packageInfoDto = new PackageInfoDto();
        packageInfoDto.setId(delivery.getId() + "_" + packageNum);
        packageInfoDto.setItems(items);

        AddressDto receiveAddress = new AddressDto();
        receiveAddress.setProvince(delivery.getReceiverProvince());
        receiveAddress.setCity(delivery.getReceiverCity());
        receiveAddress.setDistrict(delivery.getReceiverDistrict());
        receiveAddress.setDetail(delivery.getReceiverDetailAddress());

        UserInfoDto receiver = new UserInfoDto();
        receiver.setName(delivery.getReceiverName());
        receiver.setMobile(delivery.getReceiverMobile());
        receiver.setPhone(delivery.getReceiverMobile());
        receiver.setAddress(receiveAddress);
        receiver.setOaid(delivery.getOaid());

        TradeOrderInfoDto tradeOrderInfoDto = new TradeOrderInfoDto();
        tradeOrderInfoDto.setObjectId(delivery.getCode());
        switch (type) {
            //京东获取面单信息时，在TradeOrderInfoDto类里新增TradeOrderInfoDto.JdWaybillDTO内部类属性
            case 2:
                dto.setSheetMerchantCode(shop.getPlatformShopCode());
                dto.setMallMerchantCode(shop.getMerchantsCode());
                TradeOrderInfoDto.JdWaybillDTO jdWaybillDTO = getJdWaybillDTO(delivery.getCode(), delivery.getIsvCode() + "_" + packageNum, carriers, dto.getMallMerchantCode());
                tradeOrderInfoDto.setJdWaybillDTO(jdWaybillDTO);
                break;
            //快手获取面单信息时，在TradeOrderInfoDto类里新增TradeOrderInfoDto.GetEbillOrderRequest内部类属性
            case 6:
                TradeOrderInfoDto.GetEbillOrderRequest getEbillOrderRequest = getGetEbillOrderRequest(delivery,carriers, dto.getMallMerchantCode());
                tradeOrderInfoDto.setGetEbillOrderRequest(getEbillOrderRequest);
                break;
            case 4:
                //抖音增加产品类型
                if (StrUtil.isNotEmpty(carriers.getExpressType())) {
                    tradeOrderInfoDto.setProductType(carriers.getExpressType());
                }
                tradeOrderInfoDto.setUserId(-1L);
                break;
            default:
                tradeOrderInfoDto.setUserId(StrUtil.isNotBlank(delivery.getUserId()) ? Long.parseLong(delivery.getUserId()) : 0L);
        }

        tradeOrderInfoDto.setTemplateUrl(standardTemplateUrl);
        tradeOrderInfoDto.setOrderInfo(orderInfoDto);
        tradeOrderInfoDto.setPackageInfo(packageInfoDto);
        tradeOrderInfoDto.setRecipient(receiver);

        orderInfoDtos.add(tradeOrderInfoDto);
        dto.setTradeOrderInfoDtos(orderInfoDtos);
        return dto;
    }

    private void hedan(Delivery e) {
        if(ObjectUtil.isNotEmpty(e) && StringUtils.isNotEmpty(e.getIsvCode())){
            String[] split = e.getIsvCode().split("，|,");
            e.setIsvCode(split[0]);
        }
    }

    public TradeOrderInfoDto.GetEbillOrderRequest getGetEbillOrderRequest(Delivery delivery,Carrier carriers, String mallMerchantCode) {
        TradeOrderInfoDto.GetEbillOrderRequest getEbillOrderRequest = new TradeOrderInfoDto.GetEbillOrderRequest();
        //商家编码
        getEbillOrderRequest.setMerchantCode(carriers.getVendorCode());
        //商家名称
        getEbillOrderRequest.setMerchantName(carriers.getVendorName());
        //包裹总数量
        getEbillOrderRequest.setTotalPackageQuantity(1L);
        //区分物流公司类型 直营和加盟
        if(StrUtil.equalsAny(carriers.getOuterCode(),"POSTB","EMS","JD","SF")){
            getEbillOrderRequest.setType("0");
            //直营
            if(StrUtil.equalsAny(carriers.getOuterCode(),"SF","EMS","POSTB")){
                //面单扩展信息
                getEbillOrderRequest.setExtData(carriers.getExtData());
                if(StrUtil.equalsAny(carriers.getOuterCode(),"SF")){
                    getEbillOrderRequest.setPayMethod(Integer.valueOf(carriers.getExpressPayMethod()));
                }
            }
            if(StrUtil.equalsAny(carriers.getOuterCode(),"JD")){
                //expressProductCode：物流产品
                getEbillOrderRequest.setExpressProductCode(carriers.getExpressProductCode());
                //payMethod（付款方式）
                getEbillOrderRequest.setPayMethod(Integer.valueOf(carriers.getExpressPayMethod()));
                //（要求上门取件时间）：
                long timestamp = delivery.getGmtCreated().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
                long l = 3600000L * 12;
                getEbillOrderRequest.setReserveTime(timestamp + l);
                //要求上门取件时间结束时间
                long m = 3600000L * 24;
                getEbillOrderRequest.setReserveEndTime(timestamp + m);
            }
            //客户编码=月结卡号
            getEbillOrderRequest.setSettleAccount(carriers.getCustomerCode());
        }else{
            getEbillOrderRequest.setType("1");
            //加盟
            //网点编码
            getEbillOrderRequest.setNetSiteCode(carriers.getBranchCode());
            //网点名称
            getEbillOrderRequest.setNetSiteName(carriers.getBranchName());
        }
        return getEbillOrderRequest;
    }

    private TradeOrderInfoDto.JdWaybillDTO getJdWaybillDTO(String deliveryCode, String platformOrderNo, Carrier carriers, String mallMerchantCode) {
        TradeOrderInfoDto.JdWaybillDTO jdWaybillDTO = new TradeOrderInfoDto.JdWaybillDTO();
        //运单类型：1-普通运单；2-生鲜；3-航空
        jdWaybillDTO.setWaybillType(NUM_ONE);
        //所需运单的数量，顺丰只能传1，非顺丰快递公司最多只能传99
        jdWaybillDTO.setWaybillCount(NUM_ONE);
        //承运商编码（与providerId必填一个）,这里只填承运商编码
        jdWaybillDTO.setProviderCode(carriers.getOuterCode());
        jdWaybillDTO.setProviderId(carriers.getProviderId());
        //平台订单号，即pop订单号，脱敏项目必须穿真实的京东pop订单号
        jdWaybillDTO.setPlatformOrderNo(platformOrderNo);
        //商家编码，商家编码，是用POP商家ID
        jdWaybillDTO.setVendorCode(carriers.getVendorCode());
        //商家名称
        jdWaybillDTO.setVendorName(carriers.getVendorName());
        //承运商发货网点编码
        jdWaybillDTO.setBranchCode(carriers.getBranchCode());
        //商家自有订单号
        jdWaybillDTO.setVendorOrderCode(deliveryCode);
        //销售平台；0010001代表京东平台下的订单
        jdWaybillDTO.setSalePlatform("0010001");
        jdWaybillDTO.setWeight(BigDecimal.ONE);
        jdWaybillDTO.setVolume(BigDecimal.ONE);
        //承诺时效类型；无时效默认传0
        jdWaybillDTO.setPromiseTimeType(NumConst.NUM_ZERO);
        jdWaybillDTO.setGoodsMoney(BigDecimal.ONE);
        jdWaybillDTO.setPayType(NumConst.NUM_ZERO);
        jdWaybillDTO.setShouldPayMoney(BigDecimal.ZERO);
        jdWaybillDTO.setNeedGuarantee(false);
        jdWaybillDTO.setGuaranteeMoney(BigDecimal.ZERO);
        jdWaybillDTO.setPin(StrUtil.EMPTY);
        jdWaybillDTO.setSalePlat("0010001");
        //商家编码/青龙业主号/配送编码/月结编码
        jdWaybillDTO.setCustomerCode(mallMerchantCode);
        jdWaybillDTO.setOrderId(deliveryCode);
        jdWaybillDTO.setThrOrderId(deliveryCode);
        jdWaybillDTO.setPackageCount(NUM_ONE);
        return jdWaybillDTO;
    }

    /**
     * 查询列表
     * @param splitOrderDTO
     * @return
     */
    @Override
    public List<SplitOrderVO> queryList(SplitOrderDTO splitOrderDTO){
        return this.baseMapper.queryList(splitOrderDTO);
    }

    /**
     * 查询合计,包含总数
     * @param splitOrderDTO
     * @return
     */
    @Override
    public SplitOrderVO queryListSum(SplitOrderDTO splitOrderDTO){
        return this.baseMapper.queryListSum(splitOrderDTO);
    }

    /**
     * 打印拆单运单
     * @author rfwang
     * @date 2022/1/12 16:46
     * @param splitOrderDTO
     */
    @Override
    public List<SplitOrderVO> printSplitExpress(SplitOrderDTO splitOrderDTO){
        List<SplitOrderVO> splitOrderVOS = queryList(splitOrderDTO);
        Delivery delivery = deliveryService.getOne(new LambdaQueryWrapper<Delivery>().select(Delivery::getCode,Delivery::getCarrierCode,Delivery::getSourcePlatformCode)
                .eq(Delivery::getCode, splitOrderDTO.getDeliveryCode()));
        Carrier carrier = carrierCache.getCarrier(delivery.getCarrierCode());
        Shop shop = shopCache.getShop(carrier.getShopCode());
        String token = shop.getAccessToken();

        //获取订单明细信息
        DeliveryItemDTO deliveryItemDTO = new DeliveryItemDTO();
        deliveryItemDTO.setPageNum(1);
        deliveryItemDTO.setPageSize(9999);
        deliveryItemDTO.setDeliveryCode(delivery.getCode());
        List<DeliveryItemVO> deliveryItemVOList = this.deliveryItemService.queryList(deliveryItemDTO);

        if (StrUtil.equalsAny(delivery.getSourcePlatformCode(),"DY","DYXD")&&StrUtil.isNotBlank(token)) {
            splitOrderVOS.stream().forEach(r -> {
                r.setPlatformType(carrier.getPlatformType());
                r.setDeliveryItemVOList(deliveryItemVOList);
                //前端打印已有waybillCode字段，拆单的面单号也用该字段打印
                r.setWaybillCode(r.getSplitWaybillCode());
                String printDataStr = r.getPrintData();
                String p = DouyinUtil.getPrintParam(token);
                Map<String, String> printData = JSONUtil.toBean(printDataStr, Map.class);
                printData.put("params", p);
                printData.put("templateURL", carrier.getStandardTemplateUrl());
                r.setPrintData(JSONUtil.toJsonStr(printData));
            });
        } else {
            splitOrderVOS.stream().forEach(r -> {
                r.setPlatformType(carrier.getPlatformType());
                r.setDeliveryItemVOList(deliveryItemVOList);
                r.setWaybillCode(r.getSplitWaybillCode());
            });
        }
        return splitOrderVOS;
    }
}
